#include "sqlitehandle.h"

SqliteHandle::SqliteHandle(QObject *parent) : QObject(parent)
{
    initDb();
    creatUserTable();
}

SqliteHandle::~SqliteHandle()
{
    m_sqlDB.close();
}

bool SqliteHandle::checkExist(QString tableName, QString key,QString value)
{
    QSqlQuery sqlQuery;
    sqlQuery.setForwardOnly(true);
    QString Sql = QString("select * from '%2'").arg(tableName);
    if(!sqlQuery.exec(Sql)){
        qDebug() << "checkExist Error" << sqlQuery.lastError();
        return  false;
    }
    else {
        while(sqlQuery.next())
        {
            QString account = sqlQuery.value(key).toString();
            if(account == value){
                return true;
            }
        }
        return  false;
    }
}

QVariant SqliteHandle::getValue(QString tableName, QString key, QString value, QString targetKey)
{
    QSqlQuery sqlQuery;
    QVariant retValue;
    sqlQuery.setForwardOnly(true);
    QString Sql = QString("select * from '%2'").arg(tableName);
    if(!sqlQuery.exec(Sql)){
        qDebug() << "checkExist Error" << sqlQuery.lastError();
        return QVariant();
    }
    else {
        while(sqlQuery.next())
        {
            QString account = sqlQuery.value(key).toString();
            if(account == value){
                retValue = sqlQuery.value(targetKey);
                return  retValue;
            }
        }
        return QVariant();
    }
}

void SqliteHandle::initDb()
{
    m_sqlDB=QSqlDatabase::addDatabase("QSQLITE");
    m_sqlDB.setDatabaseName("MydemoDB.db");

    if (!m_sqlDB.open())
        qDebug() << "Error: Failed to open database." << m_sqlDB.lastError();
}

void SqliteHandle::creatUserTable()
{
    QSqlQuery sqlQuery;
    QString creatSql ="create table if not exists userTable\
            (id INTEGER PRIMARY KEY AUTOINCREMENT,\
             account varchar(20), \
             password varchar(10),\
             avatarUrl text)";
    sqlQuery.prepare(creatSql);
    if(!sqlQuery.exec())
        qDebug() << "Error: Fail to create table." << sqlQuery.lastError();
}

